package com.hn.opencv;

import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.utils.Converters;

import java.util.List;

/**
 *  透视变换
 * @author 时刻在奔跑
 */
public class PerspectiveTransform {

    public static void main(String[] args) {
        String srcImgPath = "/home/IdeaProjects/opencv-java/src/main/resources/weixiaobao.png";
        String x1 = "376,133";
        String x2 = "205,422";
        String x3 = "29,316";
        String x4 = "194,26";
        String destImgPath = "/home/IdeaProjects/opencv-java/src/main/resources/test5.png";

        perspectiveTransform(srcImgPath,x1,x2,x3,x4,destImgPath);
    }

    private static void perspectiveTransform(String srcImgPath,String x1, String x2,
                                             String x3,String x4, String destImgPath){
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

        Mat src = Imgcodecs.imread(srcImgPath);
        // 读取图像到矩阵中,取灰度图像
        if (src.empty()) {
            return;
        }
        try {
            Mat dst = new Mat();

            List<Point> listSrcs = java.util.Arrays.asList(getPoint(x1), getPoint(x2),
                    getPoint(x3), getPoint(x4));
            Mat srcPoints = Converters.vector_Point_to_Mat(listSrcs, CvType.CV_32F);

            List<Point> listDsts = java.util.Arrays.asList(new Point(0, 0), new Point(1011, 0),
                    new Point(1011, 638), new Point(0, 638));

            Mat dstPoints = Converters.vector_Point_to_Mat(listDsts, CvType.CV_32F);

            Mat perspectiveMmat = Imgproc.getPerspectiveTransform(srcPoints, dstPoints);

            Size size = new Size(new Point(1011, 638));
            Imgproc.warpPerspective(src, dst, perspectiveMmat, size, Imgproc.INTER_LINEAR);

            Mat gray = gray(dst);
            Imgcodecs.imwrite(destImgPath, gray);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Point getPoint(String points) {
        if (points == null || "".equals(points)) {
            throw new NullPointerException("坐标参数为空");
        }

        String[] split = points.split(",");
        if (split.length == 0) {
            throw new NullPointerException("坐标参数为空");
        }
        return new Point(Double.valueOf(split[0]), Double.valueOf(split[1]));
    }


    /**
     * 作用：灰度话
     *
     * @param src Mat矩阵图像
     * @return
     */
    public static Mat gray(Mat src) {
        Mat gray = new Mat();
        if (src.channels() == 3) {
            Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);
            src = gray;
        } else {
            System.out.println("The Image File Is Not The RGB File!");
        }
        return src;
    }
}
